select  (${rooms}) rooms, year((date(minDate.date) + INTERVAL (@rownum) DAY)) year,
        month((date(minDate.date) + INTERVAL (@rownum) DAY)) month,
        day((date(minDate.date) + INTERVAL (@rownum) DAY)) day,
       ((select avg((p.price_value - (select sp.price_value from price sp where sp.realty_object_id = ro.id and sp.date < p.date order by sp.date desc limit 1)))
            from realty_object ro
            join flat_details fd on fd.id = ro.flat_details_id and fd.rooms = ${rooms}
            join price p on p.realty_object_id = ro.id
            where if((select sp.date from price sp where sp.realty_object_id = ro.id and  sp.date > p.date limit 1) is null, (date(minDate.date) + INTERVAL (@rownum-1) DAY)  = date(p.date),
                    (date(minDate.date) + INTERVAL (@rownum-1) DAY) >= date(p.date)
                   and
                    (date(minDate.date) + INTERVAL (@rownum-1) DAY)
                   <
                    date((select sp.date from price sp where sp.realty_object_id = ro.id and  sp.date > p.date limit 1))
                )

        order by p.realty_object_id asc
    )) price
  from (SELECT @rownum:=0) r, price nil
join (select min(sp.date) date from price sp) minDate
join (select (max(sp.date)) date  from price sp) maxDate
where (date(minDate.date) + INTERVAL (@rownum:=@rownum+1) DAY) <= maxDate.date
